import threading
import time
import tkinter as tk

lock = threading.Lock()
warehouse = []
warehouse_size = 10

def warehouse_in(item):
    global warehouse
    with lock:
        if len(warehouse) < warehouse_size:
            warehouse.append(item)
            return {'status': 'ok', 'data': item}
        else:
            return {'status': 'full', 'data': None}

def warehouse_out():
    global warehouse
    if warehouse:
        return {'status': 'ok', 'data': warehouse.pop()}
    else:
        return {'status': 'empty', 'data': None}

class BufferVisualizer:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("缓冲池可视化")
        self.root.geometry("300x150")
        self.buffer_size = warehouse_size
        self.buffer = warehouse
        self.a_running = False
        self.b_running = False

        self.buffer_label = tk.Label(self.root, text="缓冲池：")
        self.buffer_label.pack()

        self.buffer_display = tk.Label(self.root, text=str(self.buffer))
        self.buffer_display.pack()

        self.a_button = tk.Button(self.root, text="开启输入", command=self.toggle_a)
        self.a_button.pack()

        self.b_button = tk.Button(self.root, text="开启输出", command=self.toggle_b)
        self.b_button.pack()

    def toggle_a(self):
        self.a_running = not self.a_running
        if self.a_running:
            self.a_button.config(text="关闭输入")
            threading.Thread(target=self.start_a_loop, daemon=True).start()
        else:
            self.a_button.config(text="开启输入")

    def toggle_b(self):
        self.b_running = not self.b_running
        if self.b_running:
            self.b_button.config(text="关闭输出")
            threading.Thread(target=self.start_b_loop, daemon=True).start()
        else:
            self.b_button.config(text="开启输出")

    def start_a_loop(self):
        i = 1
        while self.a_running:
            result = warehouse_in(f"{i}产品")
            self.update_display()
            if result['status'] == 'full':
                self.buffer_label.config(text="缓冲池已满")
            elif result['status'] == 'ok' and self.buffer_label.cget('text') == "缓冲池为空":
                self.buffer_label.config(text="缓冲池：")
            i += 1
            time.sleep(1)

    def start_b_loop(self):
        while self.b_running:
            result = warehouse_out()
            self.update_display()
            if result['status'] == 'empty':
                self.buffer_label.config(text="缓冲池为空")
            elif result['status'] == 'ok' and self.buffer_label.cget('text') == "缓冲池已满":
                self.buffer_label.config(text="缓冲池：")
            time.sleep(1)

    def update_display(self):
        self.buffer_display.config(text=str(self.buffer))
        self.root.update()

    def run(self):
        self.root.mainloop()

if __name__ == "__main__":
    visualizer = BufferVisualizer()
    visualizer.run()